package com.yang.strategy.flter;

import com.yang.common.constant.CacheConstant;
import com.yang.common.model.StandardSubmit;
import com.yang.strategy.client.BeaconCacheClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author yangyongsheng
 * @date 2024/9/1 23:42
 * @description
 */
@Component
@Slf4j
public class StrategyFilterContext {

    // 泛型注入，拿到所有的校验信息。策略模式 + 责任链
    @Autowired
    private Map<String, StrategyFilter> stringStrategyFilterMap;

    // 注入CacheClient
    @Autowired
    private BeaconCacheClient cacheClient;

    //缓存中保存的key
    private final String CLIENT_FILTERS = "clientFilters";

    /**
     * 当前check方法用于管理校验链的顺序
     */
    public void strategy(StandardSubmit submit) {
        //1、 基于Redis获取客户对应的校验信息
        String filters = cacheClient.hgetString(CacheConstant.CLIENT_BUSINESS + submit.getApikey(), CLIENT_FILTERS);

        //2、健壮性校验后，基于逗号分隔遍历
        String[] filterArray;//可以在if中对变量进行赋值
        if (StringUtils.isNotBlank(filters) && (filterArray = filters.split(",")).length > 0) {
            // 到这，filterArray不为null，并且有数据
            for (String strategy : filterArray) {
                StrategyFilter strategyFilter = stringStrategyFilterMap.get(strategy);
                if (strategyFilter != null) {
                    strategyFilter.strategy(submit);
                }
            }
        }
    }
}
